package com.li.springbootproject.spring.beanfactorypostprocessor;

import com.lidong.toolkit.constant.LogConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 3/12/2022 5:13 PM
 */
public class EngineFactory implements FactoryBean<CarEngine>, BeanNameAware, InvocationHandler {

    private static final Logger logger = LoggerFactory.getLogger(EngineFactory.class);

    private String name;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if ("fire".equalsIgnoreCase(method.getName())) {
            logger.info(LogConst.LOG_SUCCESS_PREFIX + "here is invoke  engine:" + method.getName());
        }
        if ("close".equalsIgnoreCase(method.getName())) {
            logger.info(LogConst.LOG_SUCCESS_PREFIX + "here is invoke  engine:" + method.getName());
        }
        return null;
    }

    @Override
    public void setBeanName(String name) {
        this.name = name;
    }

    /**
     * 获取引擎 CarEngine 的代理对象
     *
     * @return
     */
    @Override
    public CarEngine getObject() {
        logger.info(LogConst.LOG_SUCCESS_PREFIX + "EngineFactory  to build Engine01 , EngineFactory :" + name);
        CarEngine carEngine = (CarEngine) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{CarEngine.class}, this);
        return carEngine;
    }

    @Override
    public Class<?> getObjectType() {
        return CarEngine.class;
    }

    /**
     * 是否是单例 Bean
     *
     * @return
     */
    @Override
    public boolean isSingleton() {
        return true;
    }
}
